package com.dou.sample.opengl_project.utls;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;

import static android.opengl.GLES20.GL_LINEAR;
import static android.opengl.GLES20.GL_LINEAR_MIPMAP_LINEAR;
import static android.opengl.GLES20.GL_TEXTURE_2D;
import static android.opengl.GLES20.GL_TEXTURE_MAG_FILTER;
import static android.opengl.GLES20.GL_TEXTURE_MIN_FILTER;
import static android.opengl.GLES20.glBindTexture;
import static android.opengl.GLES20.glDeleteTextures;
import static android.opengl.GLES20.glGenTextures;
import static android.opengl.GLES20.glGenerateMipmap;
import static android.opengl.GLES20.glTexParameteri;

/**
 * Created by Dou on 2018/1/16.
 */

public class TextureHelper {

    private static final String TAG = TextureHelper.class.getSimpleName();

    public static int loadTexture(Context context, int resource){
        // 获得纹理对象id
        int[] textureObjectId = new int[1];
        glGenTextures(1, textureObjectId, 0);
        if (textureObjectId[0] == 0){
            return 0;
        }

        // 创建位图时不要被缩放
        BitmapFactory.Options bitmapOption = new BitmapFactory.Options();
        bitmapOption.inScaled = false;

        // opengl不能识别被压缩的图片，将图片转换为位图
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resource, bitmapOption);

        if (bitmap == null){
            glDeleteTextures(1, textureObjectId, 0);
            return 0;
        }

        // 告诉OpenGL后边的纹理调用应用到哪个对象上
        glBindTexture(GL_TEXTURE_2D, textureObjectId[0]);

        // 纹理过滤
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        // 加载位图到opengl
        GLUtils.texImage2D(GL_TEXTURE_2D, 0, bitmap, 0);
        // 位图使用完释放内存
        bitmap.recycle();

        glGenerateMipmap(GL_TEXTURE_2D);

        glBindTexture(GL_TEXTURE_2D, 0);

        return textureObjectId[0];
    }
}
